<?php
namespace app\merb\controller;


use app\common\model\ClueProgress;
use think\Db;

class Merchant extends Base
{

    //基本信息
    public function index(){
        $info = db('merchant')->where('id',session('aid'))->find();
        if($info['status']!=1){
            session(null);
            cookie(null);
            $this->redirect(url('Login/login'));
        }
        $products = model('Product')->where('status',1)->column('name','id');

        $this->assign('info',$info);
        $this->assign('products',$products);
        return $this->fetch();
    }


    //列表
    public function lists()
    {

        $mer_name = input('mer_name','');
        $phone = input('phone','');
        $username = input('username','');
        $page = input('page','');
        $limit = input('limit','');

//        $map=[];
        $map['a.mer_id'] = session('aid');
        if($mer_name != ''){
            $map['a.mer_name'] = ['like','%'.$mer_name.'%'];
        }
        if($phone != ''){
            $map['a.phone'] = $phone;
        }
        if($username != ''){
            $map['a.username'] = $username;
        }

        // 查询条件end

//        $feild='b.clue_name,b.age,b.phone';
        $lists = model('MerchantSub')->alias('a')
            ->where($map)->page($page,$limit)
            ->order('a.id desc')
            ->select();

        $total= model('MerchantSub')->alias('a')
            ->where($map)->count();


        foreach ($lists as $k=>$v){

        }

        return json([
            'code'=>200,
            'data' => $lists,
            'total' => $total,
        ]);

    }

    //切换状态
    public function changeStatus(){
        $id = input('id');
        $status = input('status');

        $aid=session('aid');
        $isOK=db('merchant_sub')->where('mer_id',$aid)->where('id',$id)->update(['status'=>$status,'update_time'=>time()]);
        if($isOK){
            return json(['code'=>200,'msg'=>'切换成功']);
        }else{
            return json(['code'=>400,'msg'=>'切换失败']);
        }
    }


    //添加编辑页面
    public function add(){
        $aid=session('aid');
        $id = input('id');
        if(!empty($id)){
            $info=Db::name('merchant_sub')->where('id',$id)->find();
            if($info['mer_id']==$aid){
                $this->assign('info',$info);
            }
        }
        return $this->fetch();
    }

    //添加编辑页面
    public function save(){
        $aid=session('aid');
        $postData=input('post.');
        if(!empty($postData['id'])){
            $isData=model('MerchantSub')->where('id',$postData['id'])->find();
            if (!empty($isData)&&$isData['mer_id']==$aid){
                $id=$postData['id'];
                unset($postData['id']);
                if(empty($postData['password'])){
                    $postData['password'];
                }
                $isOK=model('MerchantSub')->where('id',$id)->update($postData);
            }else{
                return json(['code'=>400,'msg'=>'ID错误']);
            }
        }else{
            if(empty($postData['password'])){
                return json(['code'=>400,'msg'=>'密码不能为空']);
            }
            $isData=model('MerchantSub')->where('username',$postData['username'])->find();
            if($isData){
                return json(['code'=>400,'msg'=>'该账号已存在']);
            }
            $postData['mer_id']=$aid;
            $isOK=model('MerchantSub')->save($postData);
        }
        if($isOK){
            return json(['code'=>200,'msg'=>'保存成功']);
        }else{
            return json(['code'=>400,'msg'=>'保存失败']);
        }
    }

    //删除
    public function del(){
        $id = input('id');//记录id
        if(empty($id)){
            return json(['code'=>400,'msg'=>'ID错误']);
        }

        $minfo=db('MerchantSub')->where('id',$id)->find();
        $aid=session('aid');
        if(empty($minfo)||$minfo['mer_id']!=$aid){
            return json(['code'=>400,'msg'=>'非法请求']);
        }
        $result =model('MerchantSub')->destroy($id);
        if($result){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>400,'msg'=>'删除失败']);
        }
    }

    public function clueIndex(){
        $info = db('merchant')->where('id',session('aid'))->find();
        if($info['status']!=1){
            session(null);
            cookie(null);
            $this->redirect(url('Login/login'));
        }
        $products = model('Product')->where('status',1)->column('name','id');

        $this->assign('info',$info);
        $this->assign('products',$products);
        return $this->fetch();
    }

    public function clue()
    {
        $aid=session('aid');
        $mer_name = input('mer_name','');
        $mer_id = input('mer_id','');
        $clue_name = input('clue_name','');
        $phone = input('phone','');
        $source = input('source','0');
        $times = input('times','');
        $page = input('page','');
        $limit = input('limit','');
        $pro_id = input('pro_id','');
        $cityname = input('cityname','');

//        $map=[];
        $map['a.mer_id'] = $aid;
        if($clue_name != ''){
            $map['b.clue_name'] = ['like','%'.$clue_name.'%'];
        }

        if(!empty($mer_name)){
            $merIdArr=model('MerchantSub')->where('mer_id',$aid)->where('mer_name','like','%'.$mer_name.'%')->column('id');
            $map['a.mer_id_sub'] = ['in',$merIdArr];
        }

        if($mer_id != ''){
            $map['a.mer_id_sub'] = $mer_id;
        }

        if($phone != ''){
            $map['b.phone'] = $phone;
        }
        if($source != '0'){
            $map['b.source'] = $source;
        }
        if($pro_id!=''){
            $map['a.pro_id']=$pro_id;
        }

        //模糊查询城市
        if(!empty($cityname)){
            $cityIdArr=Db::name('city')->field('id,type,pid')->where('name','like',$cityname."%")->where('type',2)->find();
            if($cityIdArr){
                $map['a.city']=$cityIdArr['pid'].'-'.$cityIdArr['id'];
            }else{
                $map['a.city']=0;
            }
        }

        $config = model('SystemConfig')->getInfoByMap(['id'=>3]);
        if(!empty($config)&&$config['status']==1&&!empty($config['extra'])){
            $dayTime=$config['extra']*3600*24;
            $star_time=strtotime(date('Y-m-d'))-$dayTime;
            $map['a.create_time'] = ['>=',$star_time];
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $starTime=strtotime($time_arr[0]);
            if(empty($star_time)){
                $star_time=$starTime;
            }else{
                if($star_time<$starTime){
                    $star_time=$starTime;
                }
            }

            $map['a.create_time'] = ['between',[$star_time,strtotime($time_arr[1])]];
        }
        // 查询条件end


//        $feild='b.clue_name,b.age,b.phone';
        $lists = model('clue_log_sub_mer')->alias('a')
            ->field('e.mer_name,a.id,b.clue_name,b.age,b.gender,a.phone,a.city,a.charge_type,a.price,a.status,a.create_time,b.remark,b.apply_limit,c.name pro_name,b.type,d.show_channel,a.show_city,b.house,b.car,b.public_funds')
            ->join('clue b','a.clue_id=b.id','LEFT')
            ->join('product c','c.id=a.pro_id','LEFT')
            ->join('account d','d.adv_id=a.adv_id','LEFT')
            ->join('merchant_sub e','e.id=a.mer_id_sub','LEFT')
            ->where($map)->page($page,$limit)
            ->order('a.id desc')
            ->select();

        $total= model('clue_log_sub_mer')->alias('a')
            ->join('clue b','a.clue_id=b.id')
            ->where($map)->count();

        $channels = $this->getChannelArray();

        foreach ($lists as $k=>$v){
            if(!empty($v['show_city'])){
                $lists[$k]['city']=$v['show_city'];
            }else{
                if($v['city'] != ''){
                    $ids = explode('-',$v['city']);
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $lists[$k]['city'] = $prov;
                    }else{
                        $lists[$k]['city'] = $prov.'-'.$city;
                    }
                }
            }
            $lists[$k]['gender']=config('clue.gender')[$v['gender']];
            $lists[$k]['charge_type'] = config('clue.charge_types')[$v['charge_type']];

            if(!empty($v['show_channel'])){
                $lists[$k]['channel_name'] = $v['show_channel'];
            }else{
                $lists[$k]['channel_name'] = $channels[$v['type']];
            }
            $content='';
            if(!empty($v['car'])){
                $content=$v['car'];
            }
            if(!empty($v['house'])){
                $content=$v['house'];
            }
            if(!empty($v['public_funds'])){
                $content='公积金：'.$v['car'];
            }
            $lists[$k]['content']=$content;

            if(empty($v['remark'])){
                $lists[$k]['remark_data']=[];
            }else{
                $remark=json_decode($v['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if(strpos($kk, '城市') !== false){
                            }else{
                                $remarkArr[]=$kk.'：'.$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($v['type']==1){
                                if(strpos($vv['name'], '城市') !== false){
                                }else{
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    if(strpos($vv['name'], '城市') !== false){
                                    }else{
                                        $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                    }
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr=[];
                    $remarkArr[]=$v['remark'];

                }
                $lists[$k]['remark_data']=$remarkArr;
            }

        }

        return json([
            'code'=>200,
            'data' => $lists,
            'total' => $total,
        ]);
    }

}
